package com.example.travelservlet.food.service;

import com.example.travelservlet.entity.Entertainment;
import com.example.travelservlet.entity.Food;
import com.example.travelservlet.food.repository.FoodRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @author hxy
 * @date 2022/11/6 16:44
 */
@Service
public class FoodServiceImpl implements FoodService{
    @Autowired
    private FoodRepository foodRepository;
    @Override
    public Page findFoodsBySceneryIds(List<String> sceneryIds, Pageable pageable) {
        Specification<Food> specification = new Specification<Food>() {
            @Override
            public Predicate toPredicate(Root<Food> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (sceneryIds.size() != 0){
                    for (String sceneryId : sceneryIds){
                        predicates.add(criteriaBuilder.or(criteriaBuilder.equal(root.get("sceneryId"),sceneryId)));
                    }
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        Page page = foodRepository.findAll(specification,pageable);
        return page;
    }


}
